package 同步辅助类;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {



    public static void main(String[] args) {
        ExecutorService service= Executors.newCachedThreadPool();
        final Semaphore semaphore=new Semaphore(5);
        for (int i=0;i<20;i++){
            final int no=i;
            Runnable runnable=new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        System.out.println("accessing:"+no);
                        System.out.println(Thread.currentThread().getName());
                        Thread.sleep((long) (Math.random()*10000));
                        semaphore.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            service.execute(runnable);
        }
        service.shutdown();
    }
}
